'''
Created on 18.7.2011

@author: gilead

Transforms messages from the server into events
'''

from pyreddwarf.pyreddwarf import RedDwarfSimpleClient, BytesArray
from pyreddwarf.reddwarfprotocol import *
from direct.task import Task

from protocol import *
from Messages import Messages

class RDServer(object):
    
    def __init__(self, username, password):
        self.readinglist = []
        self.writinglist = []
        
        taskMgr.add(self.TaskReaderPolling,"Poll the connection reader",-40)
        taskMgr.add(self.TaskWriterPolling,"Poll the connection writer",-40)
        
        self.client = RedDwarfSimpleClient("127.0.0.1",62964)
    
        self.writinglist.append(self.client.socket)
        self.readinglist.append(self.client.socket)
        
        self.client.connect()
        self.client.login(username, password)
        
        self.client.registerListener(self.RecieveMessage, "on_" + SESSION_MESSAGE_MSG)
        self.client.registerListener(self.RecieveChannelMessage, "on_" + CHANNEL_MESSAGE_MSG)
    
    def SendMoveOrder(self, guid, x, y):
        buf = Messages.CreateMovementOrderPkt(guid, x,y)
        self.client.sessionSend(buf)
    
    def RecieveChannelMessage(self, event, client):
        message = BytesArray('c',event.message)#todo create with a init
        command = ord(message.readByte())
        
        if command == MOVE_SHIP_CODE:
            guid,x,y,vel,heading = Messages.ReadShipMovePkt(message)
            messenger.send(MOVE_SHIP_MSG, [guid,x,y, vel, heading])
        elif command == FIRE_TURRET_CODE:
            shooterGuid, shooterTurretID, targetGuid, offsetlength, offsetwidth = Messages.readTurretFirePkt(message)
            messenger.send(FIRE_TURRET_MESSAGE, [shooterGuid, shooterTurretID, targetGuid, offsetlength, offsetwidth])
    
    def RecieveMessage(self, event, client):
        message = BytesArray('c',event.message)#todo create with a init
        command = ord(message.readByte())
        
        if command == CREATE_SHIP_CODE:
            guid,typeid,x,y,ownerid = Messages.ReadShipCreationPkt(message)
            z = 0
            #print guid, typeid, x, y, z,ownerid
            messenger.send(CREATE_SHIP_MSG, [x, y, z, guid, ownerid, typeid])
        elif command == INFORM_USER_ID_CODE:
            id = Messages.readUserIDPkt(message)
            messenger.send(INFORM_USER_ID_MESSAGE, [id])
    
    def TaskReaderPolling(self,taskdata):
        for x in self.readinglist:
            if x.connected and x.readable():
                x.handle_read()
        return Task.cont
    def TaskWriterPolling(self, taskdata):
        for x in self.writinglist:
            if x.connected and x.writable():
                x.handle_write()
        return Task.cont